﻿using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace LC.Common
{
    /// <summary>
    /// 导出Excel
    /// </summary>
    public class ExcelExport
    {
        /// <summary>
        /// 由列模型，数据库生成电子表格
        /// </summary>
        /// <param name="ExcelColumn">列模型</param>
        /// <param name="dt">数据源</param>
        /// <param name="width">列宽</param>
        /// <returns></returns>
        public static HSSFWorkbook ExportExcel(List<ExcelColumn> ExcelColumn, DataTable dt, params int[] width)
        {
            if (ExcelColumn.Count == 0)
            {
                return null;
            }
            //列宽默认4000
            if (width == null || width.Length == 0)
            {
                width = new int[] { 4000 };
            }
            HSSFWorkbook workbook = null;
            HSSFSheet sheet = null;

            workbook = new HSSFWorkbook();
            sheet = workbook.CreateSheet("sheet1");//取第一个表
            HSSFRow Row = sheet.CreateRow(0);

            //加列头
            if (ExcelColumn.Count() > 0)
            {
                for (int i = 0; i < ExcelColumn.Count; i++)
                {
                    Row.CreateCell(i).SetCellValue(ExcelColumn[i].ColumnName);
                    sheet.SetColumnWidth(i, width[0]);
                }
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                //向单元格添值
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Row = sheet.CreateRow(i + 1);
                    for (int j = 0; j < ExcelColumn.Count; j++)
                    {
                        Row.CreateCell(j).SetCellValue((dt.Rows[i][ExcelColumn[j].ColumnCode].ToString()));
                    }
                }
            }
            return workbook;
        }
        

    }
    /// <summary>
    /// 列模型
    /// </summary>
    public class ExcelColumn
    {
        /// <summary>
        /// 数据库字段名称
        /// </summary>
        public string ColumnCode { get; set; }
        /// <summary>
        /// 列表显示名称
        /// </summary>
        public string ColumnName{ get; set; }
        public ExcelColumn()
        {

        }
        public ExcelColumn(string ColumnCode, string ColumnName)
        {
            this.ColumnCode = ColumnCode;
            this.ColumnName = ColumnName;
        }
    }
}
